<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :model="formData"
    :rules="formRules"
    label-width="80px"
  >

    <el-form-item label="评审内容" prop="threeContent">
      <div style="width: 100%;">
        <el-row :gutter="24" justify="space-between">
          <el-col :xl="6" :lg="6" :md="24" :sm="24" :xs="24">
            <div class="geometry-box">
              <div class="geometry-add" @click="handleEdit">
                <div class="icon">
                  <el-icon :size="44">
                    <folder-add />
                  </el-icon>
                  <div><span>添加评审内容</span></div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col  :xl="6" :lg="6" :md="24" :sm="24" :xs="24"
            v-for="(view, index) in viewObjs" :key="index">
            <el-card body-class="" class="image-card">
              <div>
                <div style="padding: 5px;" v-if="view.content">
                  <el-image v-if="!view.vi" style="border-radius: 5px;"
                            draggable="false"
                            @click.prevent="handleView(view)"
                            class="el-img"
                            :src="view.icon"
                            :title="'点击查看3D'"
                            fit="cover"
                  />
                  <div v-else class="container" style="height: 256px; border-radius: 5px;">
                    <div v-html="view.content"></div>
                  </div>
                </div>
                <div v-else style="padding: 5px;">
                  <el-image style="border-radius: 5px;"
                            draggable="false"
                            class="el-img"
                            :src="view.icon"
                            :title="view.name"
                            fit="cover"
                  />
                </div>
                <div style="text-align: center; margin-left: 10px;">
                  <el-button @click="handleDelete(view)">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-form-item>

    <el-form-item label="评审说明" prop="threeIntroduce">
      <el-input v-model="formData.threeIntroduce"
                :autosize="{minRows:10}"
                maxlength="1024"
                placeholder="请输评审说明"
                type="textarea"
                show-word-limit/>
    </el-form-item>

    <el-col v-if="startUserSelectTasks.length > 0">
      <el-card class="mb-10px">
        <template #header>指定审批人</template>
        <el-form
          :model="startUserSelectAssignees"
          :rules="startUserSelectAssigneesFormRules"
          ref="startUserSelectAssigneesFormRef"
        >
          <el-form-item
            v-for="userTask in startUserSelectTasks"
            :key="userTask.id"
            :label="`任务【${userTask.name}】`"
            :prop="userTask.id"
          >
            <el-select
              v-model="startUserSelectAssignees[userTask.id]"
              multiple
              placeholder="请选择审批人"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-form-item>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
    </el-form-item>
  </el-form>

  <el-dialog
    title="3D模型选择"
    v-model="showDialog"
    fullscreen
    append-to-body
    destroy-on-close
  >
    <model-select @handlerOk="selectView" @handlerCancel="cancel"/>
  </el-dialog>
</template>
<script lang="ts" setup>
import * as ThreeDApi from '@/api/bpm/threed'
import { ViewApi } from "@/api/threed";
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as DefinitionApi from '@/api/bpm/definition'
import * as UserApi from '@/api/system/user'
import {FolderAdd} from "@element-plus/icons-vue";
import modelSelect from "./model.vue"

defineOptions({ name: 'BpmOAThreeDCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const showDialog = ref(false)
/** 编辑按钮操作 */
const handleEdit = () => {
  showDialog.value = true
}
const viewObjs = ref([])
/** 删除按钮操作 */
const handleDelete = (view) => {
  for (let i = 0; i < viewObjs.value.length; i++) {
    if (viewObjs.value[i].id === view.id) {
      viewObjs.value.splice(i, 1);
      break; // 找到并删除后退出循环
    }
  }
  const viewIds = ref([])
  for (let i = 0; i < viewObjs.value.length; i++) {
    const id = viewObjs.value[i].id;
    viewIds.value.push(id);
  }
  if(viewIds.value && viewIds.value.length){
    formData.value.threeContent = viewIds.value.join(',')
  }else{
    formData.value.threeContent = undefined
  }
}
/** 预览按钮操作 */
const handleView = (view) => {
  viewObjs.value.forEach(v => {
    v.vi = false;
  })
  view.vi = true
}
const selectView = async (viewIds) => {
  if (!viewIds.value || viewIds.value.length === 0) {
    ElMessage.warning('请选择展示模型');
    return
  }

  for (const viewId of viewIds.value) {
    const viewObj =  await ViewApi.getView(viewId);
    viewObjs.value.push(viewObj);
  }

  formData.value.threeContent = viewIds.value.join(',')
  showDialog.value = false
}

const cancel = () => {
  showDialog.value = false
}

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
    threeContent: undefined,
    threeIntroduce: undefined,
})
const formRules = reactive({
    threeContent: [{ required: true, message: '评审内容不能为空', trigger: 'blur' }],
    threeIntroduce: [{ required: true, message: '评审说明不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
// 指定审批人
const processDefineKey = 'workReview' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref({}) // 发起人选择审批人的表单 Rules
const userList = ref<any[]>([]) // 用户列表

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    await startUserSelectAssigneesFormRef.value.validate()
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ThreeDApi.ThreeDVO
    // 设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }
    await ThreeDApi.createThreeD(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'BpmOAThreeD' })
  } finally {
    formLoading.value = false
  }
}

/** 初始化 */
onMounted(async () => {
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )
  if (!processDefinitionDetail) {
    message.error('评审的流程模型未配置，请检查！')
    return
  }
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
  // 设置指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    // 设置校验规则
    for (const userTask of startUserSelectTasks.value) {
      startUserSelectAssignees.value[userTask.id] = []
      startUserSelectAssigneesFormRules.value[userTask.id] = [
        { required: true, message: '请选择审批人', trigger: 'blur' }
      ]
    }
    // 加载用户列表
    userList.value = await UserApi.getSimpleUserList()
  }
})
</script>
<style lang="scss">
.geometry-box {
  position: relative;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  padding: 5px;
  overflow: hidden;
  color: #8c939d;
  text-align: center;

  .geometry-add {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 250px;
    height: 250px;
    cursor: pointer;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    .icon {
      span {
        font-size: 14px;
      }
    }

    &:hover {
      color: #409eff;
      border-color: #409eff;
    }
  }
}
.view-container {
  width: 100%;
  height: 100vh; /* 或者你想要的高度 */
  border: 1px solid #000; /* 可选，用于查看边界 */
  overflow: hidden; /* 确保内容不会溢出 */
  position: relative; /* 使iframe的绝对定位相对于这个div */
}
.view-container iframe {
  width: 100%;
  height: 100%;
  border: none; /* 去掉iframe的边框 */
  position: absolute; /* 使iframe绝对定位 */
  top: 0;
  left: 0;
}
.image-card {
  margin: 10px;
  height: auto;
  border-radius: 10px;
  position: relative;
  display: flex;
  flex-direction: column;
}
</style>
